package top.abilities.util.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @Auhtor: abilites
 * @Description 动态数据源（数据源切换）
 * @Date: 2017/9/20 14:41
 * @Modified By:
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private final static Logger _log = LoggerFactory.getLogger(DynamicDataSource.class);

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(){
        /**
         * 将 master 数据源的 key作为默认数据源的 key
         */
        @Override
        protected String initialValue() {
            return "masterDataSource";
        }
    };

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = getDataSource();
        _log.info("当前操作使用的数据源：{}", dataSource);
        return dataSource;
    }

    /**
     * @Description: 设置数据源
     * @Param: [dataSource]
     * @Return void
     * @Author abilites
     * @Date 2017/9/20 15:18
     */
    public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
    }

    /**
     * @Description: 获取数据源
     * @Param: []
     * @Return java.lang.String
     * @Author abilites
     * @Date 2017/9/20 15:17
     */
    public static String getDataSource() {
        String dataSource = contextHolder.get();
        // 如果没有指定数据源，使用默认数据源
        if (null == dataSource) {
            DynamicDataSource.setDataSource(DataSourceEnum.MASTER.getDefault());
        }
        return contextHolder.get();
    }

    /**
     * @Description: 清除数据源
     * @Param: []
     * @Return void
     * @Author abilites
     * @Date 2017/9/20 15:18
     */
    public static void clearDataSource() {

        contextHolder.remove();
    }
}
